package patterns;

// 主类，测试责任链
public class LearnChain {
    public static void main(String[] args) {
        // 责任链模式让多个处理对象（处理器）形成一条链，请求在链上传递，
        // 直到有对象处理它或者链结束，这样可以解耦请求发送者和处理者。
        LeaveRequest request = new LeaveRequest("同学", 5);
        Handler leader = new GroupLeader();
        Handler manager = new Manager();
        Handler boss = new CEO();
        // 构建责任链
        leader.setNext(manager);
        manager.setNext(boss);
        // 发起请求
        leader.handle(request);
    }
}

// 请假请求类
class LeaveRequest {
    String name;
    int days;

    public LeaveRequest(String name, int days) {
        this.name = name;
        this.days = days;
    }
}

// 抽象处理者
abstract class Handler {
    protected Handler next;

    public void setNext(Handler next) {
        this.next = next;
    }

    // 处理方法：子类实现
    public abstract void handle(LeaveRequest request);
}

// 小组长审批：1~3天
class GroupLeader extends Handler {
    @Override
    public void handle(LeaveRequest request) {
        if (request.days <= 3) {
            System.out.println("组长批准了 " + request.name + " 的 " + request.days + " 天请假");
        } else if (next != null) {
            System.out.println("组长无权处理，转交上级");
            next.handle(request);
        }
    }
}

// 经理审批：4~7天
class Manager extends Handler {
    @Override
    public void handle(LeaveRequest request) {
        if (request.days <= 7) {
            System.out.println("经理批准了 " + request.name + " 的 " + request.days + " 天请假");
        } else if (next != null) {
            System.out.println("经理无权处理，转交上级");
            next.handle(request);
        }
    }
}

// CEO审批：超过7天
class CEO extends Handler {
    @Override
    public void handle(LeaveRequest request) {
        if (request.days > 7) {
            System.out.println("CEO 批准了 " + request.name + " 的 " + request.days + " 天请假");
        } else {
            System.out.println("CEO：这事不归我管！");
        }
    }
}
